﻿using CliWrap;
using CliWrap.EventStream;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace NlpTrainApp.Bll.Uie
{
    /// <summary>
    /// uie提取业务类
    /// </summary>
    public class ExtractFewShotServiceBll
    {
        /// <summary>
        /// The CTS控制识别程序
        /// </summary>
        private CancellationTokenSource cts;
        private readonly ILogger<ExtractFewShotServiceBll> logger;
        public ExtractFewShotServiceBll(ILogger<ExtractFewShotServiceBll> logger)
        {
            this.logger = logger;
        }
        /// <summary>
        /// Stops the classify.
        /// </summary>
        public async Task RestartClassify()
        {
            cts.Cancel();
            await Task.Delay(10000);
            _ = RunClassify();
        }
        /// <summary>
        /// Runs the classify.
        /// </summary>
        public async Task RunClassify()
        {
            var cmd = Cli.Wrap("python").WithWorkingDirectory(AppContext.BaseDirectory);
            cmd = cmd.WithArguments(new[] { "serverLitieExtract.py" });
            try
            {
                cts = new CancellationTokenSource();
                await foreach (var cmdEvent in cmd.ListenAsync(cts.Token))
                {
                    switch (cmdEvent)
                    {
                        case StartedCommandEvent:
                            break;
                        case ExitedCommandEvent exited:
                            logger.LogInformation($"RunClassify{exited}");
                            break;
                        case StandardErrorCommandEvent err:
                            logger.LogInformation($"{err}");
                            break;
                        default:
                            logger.LogInformation($"{cmdEvent}");
                            break;
                    }
                }
            }
            catch (OperationCanceledException ex)
            {
                logger.LogError($"RunClassify异常{ex.Message}{ex.StackTrace}");
            }
        }
    }
}
